<template>
    <zw-modal v-model="visible" title="编辑表" width="90%" height="80%">
        <el-tabs v-model="activeName">
            <el-tab-pane label="基本信息" name="basicInfo">
                <zw-form :schema="formSchema"></zw-form>
            </el-tab-pane>
            <el-tab-pane label="字段信息" name="column">
                <ZwTemplateListEditPage :schema="columnSchema" ref="refEditList"></ZwTemplateListEditPage>
            </el-tab-pane>
        </el-tabs>
        <template #footer>
            <el-button type="primary" @click="onConfirm">确 定</el-button>
        </template>
    </zw-modal>
</template>
<script lang="ts" setup>

import { ref, onMounted } from 'vue'
import { getBaseInfoSchema } from "./BaseInfoSchema"
import { getColumnsSchema } from "./ColumnsSchema"
import request from '@/config/axios'
import { VXETable } from 'vxe-table';
import { handleTree } from '@/utils/tree'

const activeName = ref('basicInfo')
const visible = ref(false)
const refEditList = ref()
const dictOptions = ref([])
const menuOptions = ref<any>([])

const formSchema = getBaseInfoSchema(menuOptions)
const columnSchema = getColumnsSchema(refEditList, dictOptions)

const show = async (id) => {
    visible.value = true;
    const reqBody = {
        method: "get",
        url: "/infra/codegen/detail",
        params: {
            tableId: id
        }
    }

    let [data, ] = await request.request(reqBody)
    if (data) {
        formSchema.data = data.table
        refEditList.value.refGird().loadData(data.columns)
    }
}

const onConfirm = async () => {
    let [data, err] = await request.request({
        method: "put",
        url: "/infra/codegen/update",
        params: {
            table: formSchema.data,
            columns: refEditList.value.refGird().getTableData().tableData
        }
    })
    if(data){
        VXETable.modal.message({ content: '数据更新成功', status: 'success' })
        handleClose()
    }else{
        VXETable.modal.message({ content: '数据更新失败:' + err.msg, status: 'error' })
    }
}

const handleClose = () => {
    visible.value = false
}

const getDictOptions = async () => {
    const [data,] = await request.request({ method: "get", url: "/system/dict-type/list-all-simple", params: {} })
    if (data) {
        dictOptions.value = data.map(v => {
            return {
                label: v.name,
                value: v.type,
            }
        })
    }

}

const getTree = async () =>{
    const [res,] = await request.request({
        method:"get",
        url:"/system/menu/list-all-simple"
    })
    if(res){
        menuOptions.value = handleTree(res)
    }
    
}

onMounted(async () => {
    await getDictOptions()

    await getTree()
})

defineExpose({
    show
})

</script>

<style lang="less" scoped></style>